using AutoMapper;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
using SqlSugar;
using Util;

namespace API.Controllers
{
    public class Base_ActionController : BaseController
    {
        Repository<tBase_Action> _Base_Action;
        readonly IMapper _mapper;
        public Base_ActionController(Repository<tBase_Action> Base_Action, IMapper mapper)
        {
            _Base_Action = Base_Action;
            _mapper = mapper;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> Save([FromBody] SaveBase_ActionInput dto)
            {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = _mapper.Map<tBase_Action>(dto);
                InitEntity(model);
                await _Base_Action.InsertOrUpdateAsync(model);

                //页面权限
                if (dto.Actions != null && dto.Actions.Count > 0)
                {
                    await _Base_Action.DeleteAsync(x => x.FParentId == model.Id && x.FType == 2);
                    tBase_Action actionModel = new tBase_Action();
                    foreach (var item in dto.Actions)
                    {
                        actionModel = new tBase_Action();
                        actionModel.FParentId = model.Id;
                        actionModel.FType = 2;
                        actionModel.FName = item.Name;
                        actionModel.FDeleted = false;
                        actionModel.FValue = item.Val;
                        InitEntity(actionModel);
                        await _Base_Action.InsertAsync(actionModel);
                    }
                }
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_ActionController--Save:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<Base_ActionOutput>>> GetList([FromBody] Base_ActionListInput dto)
        {
            ResultMsg<List<Base_ActionOutput>> result = new ResultMsg<List<Base_ActionOutput>>();
            try
            {
                if (dto.PageNum <= 0)
                {
                    return result.Error("PageNum不能小于或等于0");
                }
                if (dto.PageSize <= 0)
                {
                    return result.Error("PageSize不能小于或等于0");
                }
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel
                {
                    PageIndex = dto.PageNum,
                    PageSize = dto.PageSize,
                };
                var exp = Expressionable.Create<tBase_Action>();
                if (!string.IsNullOrWhiteSpace(dto.Name))
                {
                    exp.And(x => x.FName.Contains(dto.Name));
                }
                var list = (await _Base_Action.GetPageListAsync(exp.ToExpression(), pageModel)).OrderBy(x => x.FSort).ToList();
                var Base_ActionOutputs = _mapper.Map<List<Base_ActionOutput>>(list);
                return result.Success(Base_ActionOutputs, pageModel.TotalCount);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_ActionController--GetList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 获取唯一
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async  Task<ResultMsg<GetMenuTheOneOutput>> GetTheOne(string id)
        {
            ResultMsg<GetMenuTheOneOutput> result = new ResultMsg<GetMenuTheOneOutput>();
            try
            {
                var model = (await _Base_Action.GetListAsync(x => x.Id == id)).Select(t => new GetMenuTheOneOutput { Id = t.Id, ParentId = t.FParentId, Name = t.FName, NeedAction = t.FNeedAction, Type = t.FType, Url = t.FUrl, Value = t.FValue, Icon = t.FIcon, Deleted = t.FDeleted, Sort = t.FSort }).FirstOrDefault();
                var actions=(await _Base_Action.GetListAsync(x => x.FParentId == id && x.FType == 2)).Select(c=>new FormAction { 
                    Id= c.Id,
                    Name = c.FName,
                    Val = c.FValue,
                }).ToList();
                model.Actions = actions;
                return result.Success(model);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_ActionController--GetTheOne:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<string>> Del(string id)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
               await _Base_Action.DeleteByIdAsync(id);
                await _Base_Action.DeleteAsync(t => t.FParentId == id && t.FType == 2);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_ActionController--Del:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 获取菜单列表(下拉框增加菜单时用到)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<Base_ActionOutput>>> GetMenuList()
        {
            ResultMsg<List<Base_ActionOutput>> result = new ResultMsg<List<Base_ActionOutput>>();
            try
            {
                var list = (await _Base_Action.GetListAsync(x => !x.FDeleted && x.FType == 0)).OrderByDescending(x => x.FSort).ToList();
                var Base_ActionOutputs = _mapper.Map<List<Base_ActionOutput>>(list);
                return result.Success(Base_ActionOutputs, list.Count);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_ActionController--GetMenuList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 获取菜单列表(树结构)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<GetMenuTreeOutput>>> GetMenuTreeList()
        {
            ResultMsg<List<GetMenuTreeOutput>> result = new ResultMsg<List<GetMenuTreeOutput>>();
            try
            {
                string parentId = "0";

                var allLst = await _Base_Action.GetListAsync(x => !x.FDeleted);

                // 分类处理
                var menuPageList = allLst.Where(x => x.FType != 2).Select(x => new GetMenuTreeOutput
                {
                    Id = x.Id,
                    Name = x.FName,
                    ParentId = x.FParentId,
                    Type = x.FType,
                    Url = x.FUrl,
                    Value = x.FValue,
                    NeedAction = x.FNeedAction,
                    Icon = x.FIcon,
                    Sort = x.FSort,
                    Actions = new List<string>()
                }).ToList();
                var permissionList = allLst.Where(x => x.FType == 2).Select(x => new
                {
                    Id = x.Id,
                    Name = x.FName,
                    Value = x.FValue,
                    ParentId = x.FParentId // 假设权限记录中有 ParentId 字段
                }).ToList();
                // 构建树结构
                var treeList = TreeHelper.BuildTree(menuPageList, parentId);

                // 将权限添加到相应的页面的 Actions 列表中
                foreach (var permission in permissionList)
                {
                    AddPermissionToPage(treeList, permission.ParentId, $"{permission.Name}({permission.Value})");
                }

                return result.Success(menuPageList);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_ActionController--GetMenuTreeList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        private void AddPermissionToPage(List<GetMenuTreeOutput> nodes, string parentId, string permissionValue)
        {
            foreach (var node in nodes)
            {
                //Console.WriteLine($"Node ID: {node.Id}, Type: {node.Type}, Children Count: {(node.Children != null ? node.Children.Count : 0)}");

                if (node.Id == parentId && node.Type == 1)
                {
                    if (!node.Actions.Contains(permissionValue))
                    {
                        node.Actions.Add(permissionValue);
                    }
                    return;
                }
                else if (node.Children != null && node.Children.Count > 0)
                {
                    // 将 List<object> 转换为 List<GetMenuTreeOutput>
                    var children = node.Children.Cast<GetMenuTreeOutput>().ToList();
                    AddPermissionToPage(children, parentId, permissionValue);
                }
            }
        }
        /// <summary>
        /// 设置角色菜单列表(树结构)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<GetMenuTreeOutput>>> SetRoleMenuTreeList()
        {
            ResultMsg<List<GetMenuTreeOutput>> result = new ResultMsg<List<GetMenuTreeOutput>>();
            try
            {
                string parentId = "0";

                var allLst = await _Base_Action.GetListAsync(x => !x.FDeleted);

                // 分类处理
                var menuPageList = allLst.Select(x => new GetMenuTreeOutput
                {
                    Id = x.Id,
                    Name = x.FName,
                    ParentId = x.FParentId,
                    Type = x.FType,
                    Url = x.FUrl,
                    Value = x.FValue,
                    NeedAction = x.FNeedAction,
                    Icon = x.FIcon,
                    Sort = x.FSort,
                    Actions = new List<string>()
                }).ToList();
                // 构建树结构
                var treeList = TreeHelper.BuildTree(menuPageList, parentId);

                return result.Success(treeList);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_ActionController--GetMenuTreeList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
    }
}
